from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout,
    QTextEdit, QPushButton,
    QLabel, QMessageBox
)
from PyQt6.QtCore import (
    Qt, QThread, pyqtSignal
)
from PyQt6.QtGui import QTextCursor
from git import Commit, NULL_TREE
from ai.ai_client import stream_commit_analysis
import logging

logger = logging.getLogger(__name__)


class AnalyzeThread(QThread):
    stream_chunk = pyqtSignal(str)
    error_occurred = pyqtSignal(str)

    def __init__(self, summary: str, message: str, diff: str):
        super().__init__()
        self.summary = summary
        self.message = message
        self.diff = diff

    def run(self):
        try:
            prompt = f"提交摘要：{self.summary}\n\n提交信息：{self.message}\n\n变更内容：\n{self.diff}"
            for chunk in stream_commit_analysis(prompt):
                self.stream_chunk.emit(chunk)
        except Exception as e:
            logger.exception("AI 分析失败")
            self.error_occurred.emit(str(e))


class CommitDetailWindow(QWidget):
    def __init__(self, commit: Commit):
        super().__init__()
        self.setWindowTitle(f"提交详情 - {commit.hexsha[:7]}")
        self.resize(800, 600)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.label = QLabel(f"提交摘要：{commit.summary}")
        self.label.setTextInteractionFlags(
            Qt.TextInteractionFlag.TextSelectableByMouse)
        self.layout.addWidget(self.label)

        self.text = QTextEdit()
        self.text.setReadOnly(True)

        if commit.parents:
            diff_index = commit.diff(commit.parents[0], create_patch=True)
        else:
            diff_index = commit.diff(NULL_TREE, create_patch=True)
        diff_str = ''.join(d.diff.decode('utf-8', errors='ignore')
                           for d in diff_index)

        self.text.setText(f"提交信息：\n{commit.message}\n\n变更内容：\n{diff_str}")
        self.layout.addWidget(self.text)

        self.analyze_button = QPushButton("AI 分析提交")
        self.analyze_button.clicked.connect(
            lambda: self.run_ai_analysis(commit.summary, commit.message, diff_str))
        self.layout.addWidget(self.analyze_button)

    def run_ai_analysis(self, summary: str, message: str, diff: str):
        self.analyze_button.setEnabled(False)
        self.analyze_button.setText("分析中...")
        self.text.append("\n[AI 分析中，请稍候...]")
        analyzeThread = AnalyzeThread(summary, message, diff)
        self.thread = analyzeThread
        analyzeThread.stream_chunk.connect(self.append_streamed_chunk)
        analyzeThread.error_occurred.connect(self.display_analysis_error)
        analyzeThread.finished.connect(
            lambda: self.analyze_button.setText("AI 分析提交"))
        analyzeThread.finished.connect(
            lambda: self.analyze_button.setEnabled(True))
        analyzeThread.start()

    def append_streamed_chunk(self, chunk: str):
        self.text.moveCursor(QTextCursor.MoveOperation.End)
        self.text.insertPlainText(chunk)

    def display_analysis_error(self, error: str):
        QMessageBox.critical(self, "AI 分析失败", f"错误信息：{error}")
        self.analyze_button.setEnabled(True)
        self.analyze_button.setText("AI 分析提交")
